package com.sanss.log_plat.controller;

import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicLong;

@Controller
public class DataController {

    private RestTemplate restTemplate = new RestTemplate();

    private AtomicLong index = new AtomicLong(1);
    private AtomicLong lastIndex = new AtomicLong(0);

    Timer timer = new Timer();

    @GetMapping("/putdata")
    @ResponseBody
    public String putData(){
        String mapping = "{\n" +
                "  \"user\":{\n" +
                "    \"name\":\"elasticsearch\"\n" +
                "  }\n" +
                "}";
        HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(mapping,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://localhost:9200/test1/user/1", HttpMethod.PUT,entity, String.class);

        return responseEntity.getBody();
    }

    @GetMapping("/search")
    @ResponseBody
    public String search(){
        String mapping = "";
        HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(mapping,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://localhost:9200/test1/_search?pretty", HttpMethod.GET,entity, String.class);

        System.out.println(responseEntity.getBody());
        return responseEntity.getBody();
    }

    @PostMapping("/sendSMS")
    @ResponseBody
    public String sendSMS(String src, String des, String content) throws Exception{
//        @RequestBody String aaa,
//        System.out.println(index ++ + "src = " + src + " des =" + des +
//                " content = " + content);
        if(lastIndex.get()==0){
            count();
        }
        index.getAndIncrement();

        return index + "ok";
    }

    public void count(){
        timer.schedule(new TimerTask(){
            public void run(){
                if((index.get() - lastIndex.get())!=0){
                    System.out.println("每秒执行数" + (index.get() - lastIndex.get()));
                    System.out.println();
                }
                lastIndex.getAndSet(index.longValue());
            }
        }, new Date(),1000);
    }

}
